<template>
  <div class="messsage-list-view-page">
    <div class="flex-between">
      <div class="left">
        <div class="left-item" v-for="item in messagesList" :key="item.lastContentTime"
          :class="{ 'left-item-active': item.id == currentChatId }" @click="handleChangeChat(item)">
          {{ item.lastContent }}
        </div>
      </div>
      <div class="right">
        <div class="right-chat" ref="chatItemRef">
          <div v-for="item in chatList" :key="item.id">
            <template v-if="item.senderId != userId">
              <div class="message-item-left">
                <div class="message-name">用户{{ item.senderId }}</div>
                <div class="message chat-left">{{ item.content }}</div>
              </div>
            </template>
            <template v-else>
              <div class="message-item">
                <div class="message-name">{{ item.createTime }}</div>
                <div class="message chat-right">{{ item.content }}</div>
              </div>
            </template>
          </div>
        </div>
        <div style="position: relative;">
          <a-textarea type="textarea" placeholder="请输入" v-model:value="messageContent" :rows="4"></a-textarea>
          <a-button type="primary" style="position: absolute; right: 10px; bottom: 10px;"
            @click="handleSendMessage">发送</a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" name="chatMessage-chatMessage" setup>
import { ref, onMounted, nextTick, watch, unref, onBeforeUnmount } from 'vue';
import { list, deleteOne, historyList, } from './ChatMessage.api';
import { getUserInfo } from '/@/api/sys/user';
import { useUserStore } from '/@/store/modules/user';
import WebSocketClass from '/@/utils/websocket';
import { getDeviceId } from '/@/utils/util';
import { formatToDateTime } from '/@/utils/dateUtil';

const registerModal = ref();
const messageContent = ref('')
const messagesList = ref([])
const chatList = ref([])
const chatItemRef = ref();
const userStore = useUserStore();
let userId = unref(userStore.getUserInfo).id


const websocketInstance = ref<WebSocketClass | null>(null);
const isWebSocketConnected = ref(false);

const currentChatId = ref()

const loadData = async () => {
  const res = await historyList()
  if (!res || !Array.isArray(res) || res.length == 0) {
    return
  }

  messagesList.value = res
  chatList.value = res[0].childNode
  currentChatId.value = res[0].id
}

const handleChangeChat = (item) => {
  currentChatId.value = item.id
  chatList.value = item.childNode
}

const handleSendMessage = () => {
  if (messageContent.value.length == 0 || messageContent.value.trim().length == 0) {
    return
  }
  const params = {
    type: 'user_chat',
    deviceId: userId,
    data: {
      content: messageContent.value,
      createTime: formatToDateTime(new Date()),
      senderId: userId,
      receiverId: chatList.value[0].senderId,
    },
  }

  onSendMessage(params)
  chatList.value.push({
    id: chatList.value.length + 1,
    ...params.data,
  })
  console.log("chatList.value  ==>", chatList.value)

  messageContent.value = ''

  setTimeout(() => {
    scrollToBottom()
  }, 150)
}

const scrollToBottom = () => {
  if (chatItemRef.value) {
    chatItemRef.value.scrollTop = chatItemRef.value.scrollHeight;
  }
};

watch(chatList, () => {
  nextTick(() => {
    scrollToBottom();
  });
});


onBeforeUnmount(() => {
  closeWebSocket();
});

const onSendMessage = async (params) => {
  websocketInstance.value.sendMsg(JSON.stringify(params))
};


const closeWebSocket = () => {
  if (websocketInstance.value) {
    websocketInstance.value.closeSocket('关闭连接');
    console.log('WebSocket 已关闭');
  }
};

const initWebSocket = () => {
  websocketInstance.value = new WebSocketClass({});
  isWebSocketConnected.value = websocketInstance.value.isConnect.value;

  websocketInstance.value.setMessageCallback((msg) => {
    console.log('外部收到消息  11111:', msg);
    if (!msg) {
      return
    }
    const newData = JSON.parse(msg)
    if (newData.type == "heart_beat") {
      return
    }
    if (messagesList.value.length == 0) {
      loadData()
      return
    }
    if (chatList.value[0].senderId != newData.senderId) {
      reloadData()
      return
    }
    chatList.value.push({
      deviceId: userId,
      content: newData.content,
      id: newData.id,
      senderId: newData.senderId,
      receiverId: userId,
    })

    console.log('chatList.value  11111:', chatList.value);

    setTimeout(() => {
      scrollToBottom()
    }, 150)
  });
}

const reloadData = async () => {
  const res = await historyList()
  if (!res || !Array.isArray(res) || res.length == 0) {
    return
  }
  messagesList.value = res
}

onMounted(async () => {
  await loadData()

  initWebSocket()

  scrollToBottom();
})



/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}



</script>

<style lang="less" scoped>
.messsage-list-view-page {
  padding: 0;


  .left {
    width: 300px;
    height: calc(100vh - 100px);
    background: #ffffff;
    overflow: auto;
  }

  .left-item {
    margin: 10px;
    font-size: 15px;
    line-height: 15px;
    padding: 15px;
    cursor: pointer;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow-wrap: break-word;
  }

  .left-item:hover {
    background: rgb(190, 220, 249);
    border-radius: 10px;
  }

  .left-item-active {
    background: rgb(190, 220, 249);
    border-radius: 10px;
  }

  .right {
    width: 100%;
    height: 100%;
    margin: 10px;
    // background: rgb(244, 249, 251)
  }

  .right-chat {
    padding-bottom: 20px;
    height: calc(100vh - 280px);
    overflow-y: auto;
    // background: cornsilk;
  }

  .message {
    padding: 15px;
    // margin-top: 10px;
    background: #ffffff;
    font-size: 14px;
    line-height: 25px;
    max-width: 80%;
  }

  .message-item-left {
    width: 100%;
    display: flex;
    align-items: flex-start;
    flex-direction: column;
  }

  .message-item {
    width: 100%;
    display: flex;
    align-items: flex-end;
    flex-direction: column;
  }

  .message-name {
    color: #b1b1b1;
    margin: 20px 15px 5px 15px;
  }

  .message-name-right {
    text-align: right;

  }


  .chat-left {
    margin-left: 15px;
    border-radius: 10px 10px 10px 0;
  }

  .chat-right {
    margin-right: 15px;
    border-radius: 10px 10px 0 10px;
  }

  .flex-between {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }
}
</style>
